//
//  HLConposeViewController.swift
//  HLwWeibo
//
//  Created by hqhxu on 16/3/7.
//  Copyright © 2016年 hqhxu. All rights reserved.
//
/*
1.全局的item只会影响直接创建的item的颜色  不会影响自定义的。

2.自定义的按钮是否可用属性  不能影响item是否可用属性
*/

import UIKit

class HLConposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "KeyboardChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        prepareUI()
    }
    
    override func viewDidAppear(animated: Bool) {
        textView.becomeFirstResponder()
    }
    
    
    func KeyboardChangeFrame(notifify:NSNotification) {
        
        let infoDict = notifify.userInfo!
        let duration = infoDict[UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
        let frame = infoDict[UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        
        let y = UIScreen.height - frame.origin.y
        self.toolbar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(self.view).offset(-y)
        }
        /// 设置动画执行为需要的时候再执行
        UIView.animateWithDuration(duration) { () -> Void in
            self.toolbar.layoutIfNeeded()
        }
        
    }
    
    /// 设置ui相关操作
    private func prepareUI() {
        
        setUPNavgationItem()
        setUpTextView()
        setUpToolbar()  
    }
    
    private func setUpTextView() {
        
        view.addSubview(textView)
        //写第三方库的时候进来少用框架 使用系统原生的好减少依赖
        textView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(view)
        }
        
    }
    
    private func setUpToolbar() {
        view.addSubview(toolbar)
        
        toolbar.snp_makeConstraints { (make) -> Void in
            make.leading.bottom.trailing.equalTo(view)
        }
        
        toolbar.items = [UIBarButtonItem]()
        let itemSettings = [["imageName": "compose_toolbar_picture","action":"picture"],
            ["imageName": "compose_trendbutton_background","action":"trend"],
            ["imageName": "compose_mentionbutton_background","action":"mention"],
            ["imageName": "compose_emoticonbutton_background","action":"emoticon"],
            ["imageName": "compose_add_background","action":"add"]]
        for dict in itemSettings {
            let barButton = UIBarButtonItem(imageName: dict["imageName"]!)
            let fix = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
            
            toolbar.items?.append(barButton)
            toolbar.items?.append(fix)
            
            let button = barButton.customView as! UIButton
            
            let action = dict["action"]!
            
            button.addTarget(self, action: Selector(action), forControlEvents: UIControlEvents.TouchUpInside)
        }
        toolbar.items?.removeLast()
        
    }
    
    // 按钮点击事件
    @objc private func picture() {
        print("点击了图片")
    }
    @objc private func trend() {
        print("点击了#")
    }
    @objc private func mention() {
        print("点击了@")
    }
    @objc private func emoticon() {
        print("点击了笑脸")
    }
    @objc private func add() {
        print("点击了+")
    }
    
    
    private func setUPNavgationItem() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "send")
        
        navigationItem.rightBarButtonItem?.enabled = false
        
        navigationItem.titleView = setTitleLabel()
    }
    
    /// 设置导航栏上按钮的富文本
    private func setTitleLabel() -> UILabel{
        
        let label = UILabel()
        let prefix = "发微博"
        if let name = (HLAccountViewModel.shareInstance.userAcount?.screen_name) {
            let titleText = prefix + "\n" + name
            
            let nsStr = titleText as NSString
            
            let range = nsStr.rangeOfString(name)
            
            let attStr = NSMutableAttributedString(string: titleText)
            
            attStr.addAttributes([NSForegroundColorAttributeName: UIColor.lightGrayColor(),NSFontAttributeName:UIFont.systemFontOfSize(14)], range: range)
            label.attributedText = attStr
            label.font = UIFont.systemFontOfSize(16)
        }else {
            label.text = prefix
        }
        label.textAlignment = NSTextAlignment.Center
        label.numberOfLines = 0
        label.sizeToFit()
        return label
    }
    
    //MARK: 按钮点击事件
    @objc private func close() {
        textView.endEditing(true)
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func send() {
        print("点击了发送按钮")
    }
    
    lazy var toolbar:UIToolbar = UIToolbar()
    
    lazy var textView:HLPalcehodarTextView = {
        let tv = HLPalcehodarTextView()
        tv.placehodar = "分享新鲜事..."
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        tv.delegate = self
        
        return tv
    }()
    
    
}

extension HLConposeViewController:UITextViewDelegate {
    
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}






